package com.tianji.learning.task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟任务类
 *
 * @param <D>
 */
@Data
@Slf4j
public class DelayTask<D> implements Delayed {
    private D data;
    private Long deadLineNanos;

    public DelayTask(D data, Duration delayTime) {
        this.data = data;  //数据
        this.deadLineNanos = System.nanoTime() + delayTime.toNanos(); //延迟时间
    }

    /**
     * 剩余时间
     *
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(0, deadLineNanos - System.nanoTime()), TimeUnit.NANOSECONDS);
    }

    /**
     * 排序
     *
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long result = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (result > 0) {
            return 1;
        }
        if (result == 0) {
            return 0;
        }
        return -1;
    }
}
